﻿using System;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;

/// <summary>
/// 此脚本是能够将文本字符串随着时间打字或褪色显示。
/// </summary>

[RequireComponent(typeof(Text))]
[AddComponentMenu("Typewriter Effect")]
public class TypewriterEffect : MonoBehaviour
{
    public UnityEvent myEvent;

    public int charsPerSecond;

    private bool isActive;

    private float timer;

    private string words;

    private Text mText;

    private float testTime;

    private float manTime;

    private bool istestTime;

    private void OnEnable()
    {
        words = GetComponent<Text>().text;
        GetComponent<Text>().text = string.Empty;
        testTime = Time.time;
        istestTime = true;
    }

    private void OnDisable()
    {
        isActive = false;
    }

    private void ReloadText()
    {
        words = GetComponent<Text>().text;
        mText = GetComponent<Text>();
    }

    public void OnStart()
    {
        if (myEvent == null)
        {
            myEvent = new UnityEvent();
        }
        timer = 0f;
        isActive = true;
        charsPerSecond = Mathf.Max(1, charsPerSecond);
        mText = GetComponent<Text>();
    }

    private void OnStartWriter()
    {
        if (isActive)
        {
            try
            {
                mText.text = words.Substring(0, (int)((float)charsPerSecond * timer));
                timer += Time.deltaTime * 4f;
            }
            catch (Exception)
            {
                OnFinish();
            }
        }
    }

    private void OnFinish()
    {
        isActive = false;
        timer = 0f;
        GetComponent<Text>().text = words;
        try
        {
            OnFinishEvent();
            istestTime = false;
            //Debug.Log(manTime);
        }
        catch (Exception)
        {
            Debug.Log("问题");
        }
    }

    private void OnFinishEvent()
    {
        myEvent.Invoke();
    }

    private void Update()
    {
        OnStartWriter();
        if (istestTime && Time.time - testTime > 0.1f)
        {
            manTime += 0.1f;
            testTime = Time.time;
        }
    }
}

